package com.example.dmgame.utils;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import com.example.dmgame.bean.GameContent;
import android.os.AsyncTask;
import android.util.Log;

public class JsonAsyncGameTask extends AsyncTask<String, Void, List<GameContent>> {
	private Callback mCallback;
	private int mRow;

	public JsonAsyncGameTask(Callback mCallback, int mRow) {
		super();
		this.mCallback = mCallback;
		this.mRow = mRow+9;
	}

	@Override
	protected List<GameContent> doInBackground(String... params) {
		// TODO Auto-generated method stub
		List<GameContent> gameContents = new ArrayList<GameContent>();
		HttpClient client = new DefaultHttpClient();
		HttpGet get = new HttpGet(params[0]);
		HttpResponse response = null;
		try {
			response = client.execute(get);
			if(response.getStatusLine().getStatusCode()==200){
				HttpEntity entity = response.getEntity();
				byte[] bytes = EntityUtils.toByteArray(entity);
				String jsonString = new String(bytes);
				
				int start = jsonString.indexOf("{");
				String jsonString2 = jsonString.substring(start);
				
				JSONObject jsonObject = new JSONObject(jsonString2);
				JSONObject data = jsonObject.getJSONObject("data");
				for(int index=0;index<mRow;index++){
					JSONObject gameContent = data.getJSONObject(index+"");
					String id = gameContent.getString("id");
					String title = gameContent.getString("title");
					String pubdate = gameContent.getString("pubdate")+"000";
					String senddate = gameContent.getString("senddate")+"000";
					String litpic = gameContent.getString("litpic");
					String typename = gameContent.getString("typename");
					String made_company = gameContent.getString("made_company");
					String release_company = gameContent.getString("release_company");
					String website = gameContent.getString("arcurl");
					String description = gameContent.getString("description");
					String terrace = gameContent.getString("terrace");
					Log.i("JsonAsyncGameTask", "---->>id:"+id);
					GameContent game = new GameContent(id, title, pubdate, senddate, litpic, typename, made_company, release_company, website, description,terrace);
					gameContents.add(game);
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return gameContents;
	}
	
	@Override
	protected void onPostExecute(List<GameContent> result) {
		// TODO Auto-generated method stub
		super.onPostExecute(result);
		mCallback.sendData(result, mRow);
	}
	
	public interface Callback{
		void sendData(List<GameContent> gameContents,int row);
	}

}
